﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer.Dts.Pipeline;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;

namespace ErrorDescription
{
    /*
     * ErrorDescription is a little translator for SSIS Error Code.
     * Just put your error code in the first textbox, and click Translate,
     * to get the description.
     */
    public partial class frmDescription : Form
    {
        public frmDescription()
        {
            InitializeComponent();
            txtErrorCode.KeyDown += new KeyEventHandler(this.txtErrorCode_KeyDown);
        }

        // Is called when user closes the window
        private void btnClose_Click(object sender, EventArgs e)
        {
            CloseForm();
        }

        // Is called when user click on Translate button
        private void btnConvert_Click(object sender, EventArgs e)
        {
            Convert();
        }

        // Called when user press Enter
        private void txtErrorCode_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                Convert();
            else if (e.KeyCode == Keys.Escape)
                CloseForm();
        }
        
        // Close 
        private void CloseForm()
        {
            this.Close();
            this.Dispose();
        }

        // Start Error Code Translation
        private void Convert()
        {
            // Create a package to retrieve its componentmetadata
            Package p = new Package();
            MainPipe mp = ((TaskHost)p.Executables.Add("DTS.Pipeline")).InnerObject as MainPipe;
            IDTSComponentMetaData90 md = mp.ComponentMetaDataCollection.New();

            txtErrorDescription.Text = "";
            // Check Error Code
            if (txtErrorCode.Text.Length == 0)
                MessageBox.Show("Please write an Error Code in the first textbox.");
            else
            {
                int iErrorCode;
                try 
                {
                    // Error Code need to be an Integer
                    iErrorCode = Int32.Parse(txtErrorCode.Text);
                }
                catch (Exception)
                {
                    MessageBox.Show("Error Code need to be an Integer.");
                    return;
                }
                try
                {
                    // Retrieve Error Description from Error Code
                    txtErrorDescription.Text = md.GetErrorDescription(iErrorCode);
                }
                catch (Exception)
                {
                    MessageBox.Show("Unknown Error Code");
                }
            }
        }
    }
}
